//  时间格式
export const nowTime = (type, date = "") => {
  if (date) {
    date.length === 13 ? date : date * 1000
  }
  let now = new Date(date ? date : new Date())
  let year = now.getFullYear()
  let month = now.getMonth() + 1 //真实的月份需要再加上1
  let day = now.getDate()
  let h = now.getHours()
  let m = now.getMinutes()
  let s = now.getSeconds()

  if (type == 1) {
    // 年月日
    return `${year}-${month.length == 2 ? month : "0" + month}-${
      day.length == 2 ? day : "0" + day
    }`
  }
  if (type == 2) {
    // 年月日 时分秒
    return `${year}-${month.length == 2 ? month : "0" + month}-${
      day.length == 2 ? day : "0" + day
    } ${h}:${m}:${s}`
  }
  if (type == 3) {
    // 时分秒
    return `$${h}:${m}:${s}`
  }
  if ((type = 4)) {
    // 周几
    const weekArr = [
      "星期一",
      "星期二",
      "星期三",
      "星期四",
      "星期五",
      "星期六",
      "星期天",
    ]
    const week = weekArr[date.getDay()]
    return week
  }
}

//校验姓名
export const isName = (name) => {
  var rgx = /^[\u4e00-\u9fa5]+|[A-Za-z]+|[\u4e00-\u9fa5]+$/
  if (!rgx.test(name)) {
    showToast({
      title: "姓名不合法",
      icon: "none",
    })
    return false
  }
  return true
}

//  校验手机号
export const isPhone = (phone) => {
  const re = /^1[0-9]{10}$/
  if (phone.length === 11) {
    if (!re.test(phone)) {
      showToast({
        title: "手机号格式不正确！",
        icon: "none",
      })
      return false
    } else {
      return true
    }
  } else {
    showToast({
      title: "手机号长度不对！",
      icon: "none",
    })
    return false
  }
}

export const showToast = (params) => {
  uni.showToast({
    title: params.title,
    icon: params.icon || "none",
    mask: params.mask === undefined ? true : params.mask,
  })
}

// 模态框
export const showModal = (params) => {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title: params.title || "",
      content: params.content,
      confirmText: params.successText || "确定", // 确认按钮
      cancelText: params.failText || "取消", // 取消按钮
      showCancel: params.showCancel === undefined ? true : params
        .showCancel,
      success: (res) => {
        resolve(res.confirm)
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

/**
 * @param {}
 * 防抖
 */
export const debounce = (fn, delay = 500) => {
  let timer = null
  return function() {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(function() {
      fn.apply(this.arguments)
      timer = null
    }, delay)
  }
}

export const formatRichText = (html) => {
  //控制小程序中图片大小
  let newContent = html.replace(/<img[^>]*>/gi, (match, capture) => {
    match = match.replace(/style="[^"]+"/gi, '').replace(
      /style='[^']+'/gi, '')
    match = match.replace(/width="[^"]+"/gi, '').replace(
      /width='[^']+'/gi, '')
    match = match.replace(/height="[^"]+"/gi, '').replace(
      /height='[^']+'/gi, '')
    match = match.replace(/margin:10rpx auto;/gi, 'margin:0 auto;')
      .replace(/height='[^']+'/gi, '')
    return match
  })
  newContent = newContent.replace(/style="[^"]+"/gi, (match, capture) => {
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(
      /width:[^;]+;/gi, 'max-width:100%;')
    // match = match.replace(/<p><br></p>/gi, '');
    return match
  })
  newContent = newContent.replace(/<br[^>]*\/>/gi, '')
  newContent = newContent.replace(
    /\<img/gi,
    '<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"'
  )
  return newContent
}

// 选择图片
export const chooseImage = (params = {}) => {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: params.count || 1, //默认1张
      sizeType: params.sizeType ? [...params.sizeType] : ['original',
        'compressed'
      ], //可以指定是原图还是压缩图，默认二者都有res
      sourceType: params.sourceType ? [...params.sourceType] : [
        'album',
        'camera'
      ], //从相册或相机选择
      success: (res) => {
        resolve(res.tempFilePaths)
      },
      fail: (err) => {
        uni.showToast({
          title: '图片选择失败，请重新选择'
        })
        reject(err)
      }
    });
  })
}

// 将数字转化时分秒
export const setHis = (times = 0) => {
  if (typeof times === 'number') {
    if (times <= 0) {
      return '00:00:00';
    } else {
      let hh = parseInt(times / 3600); //小时
      let shh = times - hh * 3600;
      let ii = parseInt(shh / 60);
      let ss = shh - ii * 60;
      return (hh < 10 ? '0' + hh : hh) + ':' + (ii < 10 ? '0' + ii : ii) +
        ':' + (ss < 10 ? '0' + ss : ss);
    }
  } else {
    return '00:00:00';
  }
}


export const UTCformat = (utc) => {
  var date = new Date(utc),
    year = date.getFullYear(),
    month = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + parseInt(
      date
      .getMonth() + 1),
    day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate(),
    hour = date.getHours() > 9 ? date.getHours() : '0' + date.getHours(),
    minutes = date.getMinutes() > 9 ? date.getMinutes() : '0' + date
    .getMinutes(),
    seconds = date.getSeconds() > 9 ? date.getSeconds() : '0' + date
    .getSeconds();
  var res = year + '-' + month + '-' + day + ' ' + hour + ':' + minutes +
    ':' +
    seconds;
  return res;
}

export const h5Copy = (content) => {
  let textarea = document.createElement('textarea');
  textarea.value = content;
  textarea.readOnly = 'readOnly';
  document.body.appendChild(textarea);
  textarea.select(); // 选择对象
  textarea.setSelectionRange(0, content.length); //核心
  let result = document.execCommand('Copy'); // 执行浏览器复制命令
  textarea.remove();
  const msg = result ? '复制成功' : '复制失败';
  showToast({
    title: msg,
    mask: false
  });
}



// 
export const formatTime = (params) => {
  const date = new Date(params)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return `${[year, month, day].map(formatNumber).join('/')} ${[
		hour,
		minute,
		second
	]
		.map(formatNumber)
		.join(':')}`
}
const formatNumber = (n) => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
